﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Collections;
using AliboboStockLib.util;

namespace AliboboStockLib.stockdata.inst
{
    public class TradeInstManager
    {
        protected static Hashtable InstCodes = null;
        
        public static void preloadInst()
        {
            if (InstCodes == null)
                InstCodes = new Hashtable();

            InstCodes.Clear();
            DbCommand cmd = SQLFactory.getInstance(0).getCommand();
            cmd.CommandText = "select * from Insts";
            DbDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                String code = rdr.GetString(1);
                String name = rdr.GetString(2);
                Guid id = rdr.GetGuid(0);
                Hashtable ht = new Hashtable();
                ht["code"] = code;
                ht["name"] = name;
                ht["id"] = id;
                InstCodes.Add(code, ht);
            }
            rdr.Close();
            cmd.Dispose();
        }
        public static bool getInstId(String code, out Guid result)
        {
            if (InstCodes == null)
                preloadInst();
            if (InstCodes.Contains(code))
            {
                Hashtable ht = (Hashtable)InstCodes[code];
                result = (Guid)ht["id"];
                return true;
            }
            result = Guid.Empty;
            return false;
        }
        public static Guid registerInst(String code, String name)
        {
            if (InstCodes == null)
                preloadInst();

            if (InstCodes.Contains(code) == false)
            {
                ArrayList al = new ArrayList();
                Hashtable ht = new Hashtable();
                ht["code"] = code;
                ht["name"] = name;
                Guid id = NewGUID.create("inst");
                ht["id"] = id;
                InstCodes.Add(code, ht);
                List<String> names = new List<string>();
                names.Add("@id");
                names.Add("@code");
                names.Add("@name");
                ArrayList ps = new ArrayList();
                ps.Add(id.ToString("B"));
                ps.Add(code);
                ps.Add(name);
                String sql = "insert into Insts (InstId,InstCode,InstName) values (@id,@code,@name)";
                DbCommand cmd = SQLFactory.getInstance(0).getCommand();

                SQLFactory.getInstance(0).executeInsert(sql, names, ps);
                return id;
            }
            else
            {
                Guid r = Guid.Empty;
                getInstId(code, out r);
                return r;
            }
        }
    }
}
